package com.zkyc.framework.website.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkyc.framework.common.constant.Constant;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.mapper.*;
import com.zkyc.framework.common.mapper.TemplateMapper;
import com.zkyc.framework.common.pojo.*;
import com.zkyc.framework.common.utils.DateUtil;
import com.zkyc.framework.common.utils.DecryptDataUtil;
import com.zkyc.framework.common.utils.JschUtils;
import com.zkyc.framework.common.utils.PageUtil;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.common.vo.website.ModuleColumnGeneratorVo;
import com.zkyc.framework.common.vo.website.TalentVo;
import com.zkyc.framework.common.vo.website.WebsitePageVo;
import com.zkyc.framework.website.client.RoleClient;
import com.zkyc.framework.website.client.UserClient;
import com.zkyc.framework.website.config.JedisPoolFactory;
import com.zkyc.framework.website.mapper.*;
import com.zkyc.framework.common.mapper.WebRefRightMapper;
import com.zkyc.framework.common.mapper.WebsiteMapper;
import com.zkyc.framework.website.service.ColumnService;
import com.zkyc.framework.website.service.WebsiteService;
import com.zkyc.framework.website.util.TokenUserUtil;
import com.zkyc.framework.website.vo.UrlAndRightVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.Date;
import java.util.stream.Collectors;

import static com.zkyc.framework.common.constant.Constant.*;
import static com.zkyc.framework.common.utils.ExecUtil.getIp;
import static com.zkyc.framework.website.util.DeployUtil.*;


/**
 * (Website)表服务实现类
 *
 * @author libingchuan
 * @since 2022-05-23 16:22:11
 */
@Slf4j
@Service("websiteService")
public class WebsiteServiceImpl implements WebsiteService {
    @Value("${zjlab.ip}")
    private String ip;

    @Value("${zjlab.username}")
    private String username;

    @Value("${zjlab.password}")
    private String password;

    @Value("${zjlab.privateKey}")
    private String privateKey;

    private static final String LOCK_KEY = REDIS_PREFIX + "DeployLock";
    private static final String LOCK_SUCCESS = "OK";

    @Resource
    private WebsiteMapper websiteMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private WebDomainUrlMapper webDomainUrlMapper;

    @Autowired
    private RoleClient roleClient;

    @Autowired
    private LinkMapper linkMapper;

    @Autowired
    private ContentMapper contentMapper;

    @Autowired
    private WebRefRightMapper webRefRightMapper;

    @Autowired
    private RightRefTemplateMapper rightRefTemplateMapper;

    @Autowired
    private ColumnService columnService;

    @Autowired

    private RoleMapper roleMapper;

    @Autowired
    private RoleRefMenuMapper roleRefMenuMapper;

    @Autowired
    private RoleRefRightMapper roleRefRightMapper;

    @Autowired
    private UserRefRoleMapper userRefRoleMapper;

    @Autowired
    private WebsiteRefRoleMapper websiteRefRoleMapper;

    @Autowired
    private TemplateMapper templateMapper;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Website queryById(Integer id) {
        return this.websiteMapper.selectById(id);
    }

    /**
     * 查询所有站点
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryList() {
        return ResultVO.data(websiteMapper.selectList(null));
    }

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryByPage(WebsitePageVo websitePageVo) {
        if (websitePageVo == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        websitePageVo.checkParam();
        String userId = TokenUserUtil.getCurrentUserId();
        if (userId == null) {
            return ResultVO.fail(ResultCode.ReLogin);
        }
        if (Constant.SUPERADMINUSERID.equals(userId)) {
            Page page = new Page(websitePageVo.getPage(), websitePageVo.getSize());
            LambdaQueryWrapper<Website> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.orderByDesc(Website::getGmtUpdated);
            return ResultVO.data(websiteMapper.selectPage(page, lambdaQueryWrapper));
        }
        List<Website> userWebsiteList = websiteMapper.getUserWebsiteList(userId);
        Page pages = PageUtil.getPages(websitePageVo.getPage(), websitePageVo.getSize(), userWebsiteList);
        return ResultVO.data(pages);
    }


    /**
     * 新增数据
     *
     * @param website 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO save(Website website) throws Exception {
        if (website == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        website.setChangeGray(0);
        List<Website> websiteList1 = websiteMapper.selectList(new QueryWrapper<Website>().eq("website_url", website.getWebsiteUrl()));
        if (!CollectionUtils.isEmpty(websiteList1)) {
            return ResultVO.fail(ResultCode.URL_EXIST);
        }
        List<Website> websiteList = websiteMapper.selectList(new QueryWrapper<Website>().eq("website_name", website.getWebsiteName()));
        if (!CollectionUtils.isEmpty(websiteList)) {
            return ResultVO.fail(ResultCode.SITE_DUPLICATION);
        }
        String currentUserId = TokenUserUtil.getCurrentUserId();
        ResultVO<?> userById = userClient.getUserById(currentUserId);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userById));
        User user = JSONObject.parseObject(jsonObject.getString("data"), User.class);
        website.setCreateUsername(user.getUsername());
        website.setGmtCreated(new Date());
        website.setGmtUpdated(new Date());
        website.setIsDeleted(NumberConstant.NUMBER_0);
        website.setStatus(NumberConstant.NUMBER_1);
        website.setUrlStatus(NumberConstant.NUMBER_0);
        int webset = websiteMapper.insert(website);

        if (webset > 0) {
            try {
                ResultVO<?> resultVO = roleClient.addWebsiteRole(website.getId(), website.getWebsiteName(), currentUserId);
                if (resultVO.getCode() == 200) {
                    return ResultVO.success(ResultCode.SUCCESS);
                } else {
                    log.error("新增失败，删除创建的网站。");
                    deleteById(website.getId());
                    return resultVO;
                }
            } catch (Exception e) {
                log.error("新增失败，删除创建的网站。");
                deleteById(website.getId());
            }
        }
        return ResultVO.fail(ResultCode.SERVE_ERROR);
    }

    //TODO
    //首先设置网站的url,接着用url为该网站设置权限,设置好之后才能新建网站
    @Override
    public ResultVO setUrlAndRight(UrlAndRightVo urlAndRightVo) {
        if (urlAndRightVo.getUrl() == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (CollectionUtils.isEmpty(urlAndRightVo.getRightIdList())) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        WebDomainUrl webDomainUrl = new WebDomainUrl();
        webDomainUrl.setWebUrl(urlAndRightVo.getUrl());
        webDomainUrlMapper.insert(webDomainUrl);
        urlAndRightVo.getRightIdList().forEach(s -> {
            WebRefRight webRefRight = new WebRefRight();
            webRefRight.setWebsiteUrl(urlAndRightVo.getUrl());
            webRefRight.setRightId(s);
            webRefRightMapper.insert(webRefRight);
        });
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 修改数据
     *
     * @param website 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO update(Website website) {
        if (website == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (queryById(website.getId()) == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        website.setGmtUpdated(new Date());
        websiteMapper.updateById(website);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    @Transactional
    public ResultVO deleteById(Integer id) {
        if (id == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (id <= 4) {
            return null;
        }
        Website website = queryById(id);
        if (website == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        websiteMapper.deleteById(id);
        webRefRightMapper.delete(new LambdaQueryWrapper<WebRefRight>().eq(WebRefRight::getWebsiteUrl, website.getWebsiteUrl()));
        websiteRefRoleMapper.delete(new LambdaQueryWrapper<WebsiteRefRole>().eq(WebsiteRefRole::getWebsiteId, website.getId()));
        List<Integer> roleIdList = getRoleId(website.getWebsiteName());
        if (!CollectionUtils.isEmpty(roleIdList)) {
            roleMapper.deleteBatchIds(roleIdList);
            roleIdList.forEach(s -> {
                roleRefRightMapper.delete(new LambdaQueryWrapper<RoleRefRight>().eq(RoleRefRight::getRoleId, s));
                roleRefMenuMapper.delete(new LambdaQueryWrapper<RoleRefMenu>().eq(RoleRefMenu::getRoleId, s));
                userRefRoleMapper.delete(new LambdaQueryWrapper<UserRefRole>().eq(UserRefRole::getRoleId, s));
            });
        }
        return ResultVO.success(ResultCode.SUCCESS);
    }

    //找到某网站下的角色列表
    public List<Integer> getRoleId(String websiteName) {
        List<Role> roles = roleMapper.selectList(null);
        List<Integer> roleIdList = new ArrayList<>();
        roles.forEach(s -> {
            String[] split = s.getRoleName().split("-");
            if (split[0].equals(websiteName)) {
                roleIdList.add(s.getId());
            }
        });
        return roleIdList;
    }

    @Override
    public ResultVO queryUrlList() {
        ArrayList<String> totalUrlListTrim = new ArrayList<>();
        ArrayList<String> urlListTrim = new ArrayList<>();
        List<String> totalUrlList = webDomainUrlMapper.selectList(null).stream().map(WebDomainUrl::getWebUrl).collect(Collectors.toList());
        totalUrlList.forEach(s ->
                totalUrlListTrim.add(s.trim())
        );
        List<String> urlList = websiteMapper.selectList(null).stream().map(Website::getWebsiteUrl).collect(Collectors.toList());
        urlList.forEach(s ->
                urlListTrim.add(s.trim())
        );
        // 差集 (list1 - list2)
        List<String> resultList = totalUrlListTrim.stream().filter(item -> !urlListTrim.contains(item)).collect(Collectors.toList());
        System.out.println(resultList);
        return ResultVO.data(resultList);
    }

    /**
     * 记录访问量
     */
    @Override
    public void insertViews(Integer webSiteId) {
        String currentTimeStr = DateUtil.getCurrentTimeStr();
        JedisPoolFactory.incr(REDIS_PREFIX + VIEWS + webSiteId + StringPool.UNDERSCORE + currentTimeStr);
    }


    @Override
    public ResultVO forbiddenWebsite(Integer websiteId, Integer type) {
        if (websiteId == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        Website website = websiteMapper.selectById(websiteId);
        website.setStatus(type);
        websiteMapper.updateById(website);
        return ResultVO.success(ResultCode.SUCCESS);
    }


    @Override
    public ResultVO getWebsiteIdByUrl(String url) {
        if (url == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        WebDomainUrl webDomainUrl = webDomainUrlMapper.selectOne(new QueryWrapper<WebDomainUrl>().eq("web_ip", url));
        if (webDomainUrl != null) {
            Website website = websiteMapper.selectOne(new QueryWrapper<Website>().eq("website_url", webDomainUrl.getWebUrl()));
            return ResultVO.data(website.getId());
        }
        String webUrl = null;
        Integer websiteId = null;
        if (url.contains("www") && url.contains(".com")) {
            webUrl = url.substring(url.indexOf("www.") + 4, url.lastIndexOf(".com"));
        }
        List<Website> websiteList = websiteMapper.selectList(null);
        for (Website website : websiteList) {
            String websiteUrl = website.getWebsiteUrl().substring(url.indexOf("www.") + 4, url.lastIndexOf(".com"));
            if (websiteUrl.equals(webUrl)) {
                websiteId = website.getId();
            }
        }
        return ResultVO.data(websiteId);
    }


    @Override
    public ResultVO queryLink() {
        List<Link> linkList = linkMapper.selectList(new QueryWrapper<Link>().orderByAsc("listorder"));
        return ResultVO.data(linkList);
    }

    @Override
    public ResultVO queryTalent() {
        List<WebContent> contents = contentMapper.queryTalent();
        List<WebContent> webContents = contents.stream().limit(7).collect(Collectors.toList());
        List<TalentVo> talentVos = new ArrayList<>();
        webContents.forEach(s -> {
            TalentVo talentVo = new TalentVo();
            talentVo.setId(s.getId());
            talentVo.setTitle(s.getContentTitle());
            talentVo.setContent(s.getContent());
            talentVo.setReleasetime(s.getPublishTime());
            talentVo.setType(0);
            talentVos.add(talentVo);
        });
        List<TalentVo> talentVoList = talentVos.stream().sorted(Comparator.comparing(TalentVo::getReleasetime).reversed()).limit(7).collect(Collectors.toList());
        return ResultVO.data(talentVoList);
    }

    @Override
    public ResultVO webChangeGray(Integer websiteId, Integer changeGray) {
        if (websiteId == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        Website website = websiteMapper.selectById(websiteId);
        website.setChangeGray(changeGray);
        websiteMapper.updateById(website);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO saveRightByTemplateId(String webUrl, Integer templateId) {
        if (StringUtils.isEmpty(webUrl) || templateId == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        webRefRightMapper.delete(new LambdaQueryWrapper<WebRefRight>().eq(WebRefRight::getWebsiteUrl, webUrl));
        List<RightRefTemplate> rightRefTemplates = rightRefTemplateMapper.selectList(new LambdaQueryWrapper<RightRefTemplate>().eq(RightRefTemplate::getTemplateId, templateId));
        List<Integer> rightIdList = rightRefTemplates.stream().map(RightRefTemplate::getRightId).collect(Collectors.toList());
        rightIdList.forEach(s -> {
            WebRefRight webRefRight = new WebRefRight();
            webRefRight.setWebsiteUrl(webUrl);
            webRefRight.setRightId(s);
            webRefRight.setGmtCreated(new Date());
            webRefRightMapper.insert(webRefRight);
        });
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO deploy(Website website) {
        if (website == null) return ResultVO.fail("请输入站点信息");
        String websiteUrl = website.getWebsiteUrl();
        if (StringUtils.isEmpty(websiteUrl)) return ResultVO.fail("请输入域名");
        if ((website.getTemplateId() == null)) return ResultVO.fail("请选择模板");
        //分布式锁
        try {
            String lockResult = JedisPoolFactory.lock(LOCK_KEY, System.currentTimeMillis() + "", 120);
            if (LOCK_SUCCESS.equals(lockResult)) {
                //生成网站前置工作
                saveRightByTemplateId(websiteUrl, website.getTemplateId());
                //生成网站的websiteId
                int websiteId = websiteMapper.getMaxWebsiteId() + 1;
                //端口号
                int port = getPort();
                int port2 = getPort();
                //生成网站
                website.setWebPath(getIp() + ":" + (TEST_IP.equals(ip) ? port2 : port));
                website.setId(websiteId);
                ResultVO resultVO = save(website);
                if (resultVO.getCode().intValue() != ResultCode.SUCCESS.getCode()) return resultVO;
                //生成栏目树
                ModuleColumnGeneratorVo moduleColumnGeneratorVo = new ModuleColumnGeneratorVo();
                moduleColumnGeneratorVo.setWebsiteId(websiteId);
                moduleColumnGeneratorVo.setTemplateId(website.getTemplateId());
                columnService.generate(moduleColumnGeneratorVo);
                //查询模板的基本内容
                Template template = templateMapper.selectById(website.getTemplateId());
                String templateName = template.getFileName();
                JschUtils jschUtils = null;
                String modifyPath = TEMPLATE_PATH + template.getFileName() + StringPool.SLASH + template.getModifyPath() + template.getModifyName();
                String tempNodifyPath = WEBSITE_PATH + template.getFileName() + StringPool.SLASH + websiteId + StringPool.SLASH + template.getModifyPath() + TEMP + template.getModifyName();
                String modifyPathPrefix = WEBSITE_PATH + template.getFileName() + StringPool.SLASH + websiteId + StringPool.SLASH + template.getModifyPath();
                String modifyName = template.getModifyName();
                try {
                    jschUtils = new JschUtils(ip, username, DecryptDataUtil.getDecryptData(privateKey, password));
                    jschUtils.connectSftp();
                    //修改模板的websiteId
                    //jschUtils.downloadFile(modifyPathPrefix, modifyName, modifyPathPrefix, TEMP + modifyName);
                    //System.out.println("下载完成");
                    //startModify(tempNodifyPath, "headers.websiteId = " + "'" + 0 + "'", "headers.websiteId = " + "'" + websiteId + "'");
                    //jschUtils.uploadFile(modifyPathPrefix, modifyName, modifyPathPrefix, TEMP + modifyName);
                    //String cmd = CD + TEMPLATE_PATH + template.getFileName() + AND + NPM_BUILD;
                    //部署前端代码
                    //jschUtils.execCmd(cmd);
                    //复制前端代码至网站文件夹
                    String cp = MAKEDIR + WEBSITE_PATH + templateName + StringPool.SLASH + websiteId + DIST + AND + CP
                            + TEMPLATE_PATH + templateName + DIST + StringPool.SLASH + StringPool.ASTERISK
                            + StringPool.SPACE + WEBSITE_PATH + templateName + StringPool.SLASH + websiteId + DIST
                            + AND + MAKEDIR + NGINX_CONFIG_PATH_PREFIX + websiteId + AND + CD + NGINX_CONFIG_PATH_PREFIX + websiteId
                            + AND + TOUCH + NGINX_CONFIG + AND + CD + NGINX_DOMAIN_CONFIG_PATH + AND + TOUCH + websiteId + NGINX_CONFIG;
                    System.out.println("cp:" + cp);
                    jschUtils.execCmd(cp);
                    //修改nginx
                    jschUtils.downloadFile(NGINX_CONFIG_PATH_PREFIX + websiteId + StringPool.SLASH, NGINX_CONFIG, NGINX_CONFIG_PATH_PREFIX, TEMP + NGINX_CONFIG);
                    jschUtils.downloadFile(NGINX_CONFIG_PATH_PREFIX + websiteId + StringPool.SLASH, NGINX_CONFIG, NGINX_DOMAIN_CONFIG_PATH, TEMP + websiteId + NGINX_CONFIG);
                    System.out.println("下载nginx_conf至" + NGINX_CONFIG_PATH_PREFIX);
                    //追加内容
                    if (!TEST_IP.equals(ip)) {
                        startAdd(NGINX_CONFIG_PATH_PREFIX + TEMP + NGINX_CONFIG, "server {\n" +
                                "        listen       443;\n" +
                                "        server_name  localhost;\n" +
                                "      #    ssl_certificate    /etc/nginx/conf.d/6864940__zhejianglab.com.pem;\n" +
                                "       # ssl_certificate_key  /etc/nginx/conf.d/6864940__zhejianglab.com.key;\n" +
                                "\n" +
                                "      #  ssl_session_cache    shared:SSL:1m;\n" +
                                "      #  ssl_session_timeout  5m;\n" +
                                "\n" +
                                "       # ssl_ciphers  HIGH:!aNULL:!MD5;\n" +
                                "       # ssl_prefer_server_ciphers  on;\n" +
                                "#        rewrite ^(.*) https://$server_name$1 permanent;\n" +
                                "         location / {\n" +
                                "            root   /etc/nginx/dist;\n" +
                                "           index  index.html index.htm;\n" +
                                "           try_files $uri $uri/ /index.html;\n" +
                                "        }\n" +
                                "\n" +
                                "        location @router {\n" +
                                "          rewrite ^.*$ /index.html last;\n" +
                                "        }\n" +
                                "\n" +
                                "        location " + template.getProxyPrefix() + " {\n" +
                                "          proxy_pass       http://10.100.28.125:8092/;\n" +
                                "          proxy_set_header X-Forwarded-Proto $scheme;\n" +
                                "          proxy_set_header X-Forwarded-Port $server_port;\n" +
                                "          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" +
                                "          proxy_set_header Upgrade $http_upgrade;\n" +
                                "          proxy_set_header Connection \"upgrade\";\n" +
                                "        }\n" +
                                "         location ~^/zj-lab {\n" +
                                "   proxy_buffering off;\n" +
                                "   proxy_set_header Host $http_host;\n" +
                                "   proxy_pass http://10.100.28.125:9000;\n" +
                                " }\n" +
                                "\n" +
                                "}");
                        //用于配置域名
                        startAdd(NGINX_DOMAIN_CONFIG_PATH + TEMP + websiteId + NGINX_CONFIG, "server {\n" +
                                "        listen       80;\n" +
                                "        server_name  " + websiteUrl + ";\n" +
                                "        rewrite ^(.*) https://$server_name$1 permanent;\n" +
                                "         location / {\n" +
                                "            root   " + WEBSITE_PATH + templateName + StringPool.SLASH + websiteId + DIST + ";\n" +
                                "           index  index.html index.htm;\n" +
                                "           try_files $uri $uri/ @router;\n" +
                                "        }\n" +
                                "\n" +
                                "        location @router {\n" +
                                "          rewrite ^.*$ /index.html last;\n" +
                                "        }\n" +
                                "        location " + template.getProxyPrefix() + " {\n" +
                                "          proxy_pass       http://10.100.28.125:8092/;\n" +
                                "          proxy_set_header X-Forwarded-Proto $scheme;\n" +
                                "          proxy_set_header X-Forwarded-Port $server_port;\n" +
                                "          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" +
                                "          proxy_set_header Upgrade $http_upgrade;\n" +
                                "          proxy_set_header Connection \"upgrade\";\n" +
                                "        }\n" +
                                "        location ~^/zj-lab {\n" +
                                "   proxy_buffering off;\n" +
                                "   proxy_set_header Host $http_host;\n" +
                                "   proxy_pass http://10.100.28.125:9000;\n" +
                                " }\n" +
                                "\n" +
                                "\n" +
                                "   }\n" +
                                "\n" +
                                "server {\n" +
                                "        listen       443 ssl;\n" +
                                "        server_name  " + websiteUrl + ";\n" +
                                "          ssl_certificate    9103700__zhejianglab.com.pem;\n" +
                                "        ssl_certificate_key  9103700__zhejianglab.com.key;\n" +
                                "\n" +
                                "        ssl_session_cache    shared:SSL:1m;\n" +
                                "        ssl_session_timeout  5m;\n" +
                                "\n" +
                                "        ssl_ciphers  HIGH:!aNULL:!MD5;\n" +
                                "        ssl_prefer_server_ciphers  on;\n" +
                                "#        rewrite ^(.*) https://$server_name$1 permanent;\n" +
                                "         location / {\n" +
                                "            root   " + WEBSITE_PATH + templateName + StringPool.SLASH + websiteId + DIST + ";\n" +
                                "           index  index.html index.htm;\n" +
                                "           try_files $uri $uri/ /index.html;\n" +
                                "        }\n" +
                                "\n" +
                                "        location @router {\n" +
                                "          rewrite ^.*$ /index.html last;\n" +
                                "        }\n" +
                                "\n" +
                                "        location " + template.getProxyPrefix() + " {\n" +
                                "          proxy_pass       http://10.100.28.125:8092/;\n" +
                                "          proxy_set_header X-Forwarded-Proto $scheme;\n" +
                                "          proxy_set_header X-Forwarded-Port $server_port;\n" +
                                "          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" +
                                "          proxy_set_header Upgrade $http_upgrade;\n" +
                                "          proxy_set_header Connection \"upgrade\";\n" +
                                "        }\n" +
                                "         location ~^/zj-lab {\n" +
                                "   proxy_buffering off;\n" +
                                "   proxy_set_header Host $http_host;\n" +
                                "   proxy_pass http://10.100.28.125:9000;\n" +
                                " }\n" +
                                "\n" +
                                "} ");
                    } else {
                        startAdd((NGINX_CONFIG_PATH_PREFIX + TEMP + NGINX_CONFIG), "server {\n" +
                                "        listen       80;\n" +
                                "        server_name  localhost;\n" +
                                "#        rewrite ^(.*) https://$server_name$1 permanent;\n" +
                                "         location / {\n" +
                                "            root   /etc/nginx/dist;\n" +
                                "           index  index.html index.htm;\n" +
                                "           try_files $uri $uri/ @router;\n" +
                                "        }\n" +
                                "\n" +
                                "        location @router {\n" +
                                "          rewrite ^.*$ /index.html last;\n" +
                                "        }\n" +
                                "        location " + template.getProxyPrefix() + " {\n" +
                                "          proxy_pass       http://10.101.116.5:8092/;\n" +
                                "          proxy_set_header X-Forwarded-Proto $scheme;\n" +
                                "          proxy_set_header X-Forwarded-Port $server_port;\n" +
                                "          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" +
                                "          proxy_set_header Upgrade $http_upgrade;\n" +
                                "          proxy_set_header Connection \"upgrade\";\n" +
                                "        }\n" +
                                "\n" +
                                "\n" +
                                "   }\n" +
                                "\n");
                        //用于配置域名
                        startAdd(NGINX_DOMAIN_CONFIG_PATH + TEMP + websiteId + NGINX_CONFIG, "server {\n" +
                                "        listen       80;\n" +
                                "        server_name  " + websiteUrl + ";\n" +
                                "#        rewrite ^(.*) https://$server_name$1 permanent;\n" +
                                "         location / {\n" +
                                "            root   " + WEBSITE_PATH + templateName + StringPool.SLASH + websiteId + DIST + ";\n" +
                                "           index  index.html index.htm;\n" +
                                "           try_files $uri $uri/ @router;\n" +
                                "        }\n" +
                                "\n" +
                                "        location @router {\n" +
                                "          rewrite ^.*$ /index.html last;\n" +
                                "        }\n" +
                                "        location " + template.getProxyPrefix() + " {\n" +
                                "          proxy_pass       http://10.101.116.5:8092/;\n" +
                                "          proxy_set_header X-Forwarded-Proto $scheme;\n" +
                                "          proxy_set_header X-Forwarded-Port $server_port;\n" +
                                "          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" +
                                "          proxy_set_header Upgrade $http_upgrade;\n" +
                                "          proxy_set_header Connection \"upgrade\";\n" +
                                "        }\n" +
                                "\n" +
                                "\n" +
                                "   }\n");
                        jschUtils.execCmd("echo \"10.101.116.5 " + websiteUrl + "\" >> /etc/hosts");
                    }
                    jschUtils.uploadFile(NGINX_CONFIG_PATH_PREFIX + websiteId + StringPool.SLASH, NGINX_CONFIG, NGINX_CONFIG_PATH_PREFIX, TEMP + NGINX_CONFIG);
                    jschUtils.uploadFile(NGINX_DOMAIN_CONFIG_PATH, websiteId + NGINX_CONFIG, NGINX_DOMAIN_CONFIG_PATH, TEMP + websiteId + NGINX_CONFIG);
                    System.out.println("上传nginx_conf");
                    String startNginxCmd = "docker run -d -p " + port + ":443 -p " + port2 + ":80 --name nginx" + websiteId + " -v "
                            + NGINX_CONFIG_PATH_PREFIX + websiteId + ":/etc/nginx/conf.d  -v " + WEBSITE_PATH + templateName + StringPool.SLASH + websiteId + DIST
                            + ":/etc/nginx/dist  -v " + NGINX_LOG_PATH + ":/var/log/nginx --restart=always  nginx:1.16.1";
                    System.out.println("startNginx:" + startNginxCmd);
                    //删掉临时文件
                    deleteDirectoryLegacyIO(new File(NGINX_DOMAIN_CONFIG_PATH + TEMP + websiteId + NGINX_CONFIG));
                    //启动docker的nginx
                    jschUtils.execCmd(startNginxCmd);
                    //启动域名的nginx
                    jschUtils.execCmd(NGINX_RELOAD);
                    jschUtils.downloadFile(modifyPathPrefix, modifyName, modifyPathPrefix, TEMP + modifyName);
                    startModify(tempNodifyPath, "headers.websiteId=\"0\"", "headers.websiteId=\"" + websiteId + "\"");
                    startModify(tempNodifyPath, "localStorage.setItem(\"websiteIdTeap\",0)", "localStorage.setItem(\"websiteIdTeap\"," + websiteId + ")");
                    jschUtils.uploadFile(modifyPathPrefix, modifyName, modifyPathPrefix, TEMP + modifyName);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (Objects.nonNull(jschUtils)) jschUtils.disconnect();
                }
                return ResultVO.data("部署完成,访问地址:" + ip + ":" + (TEST_IP.equals(ip) ? port2 : port));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JedisPoolFactory.delete(LOCK_KEY);
        }
        return ResultVO.fail(ResultCode.DEPLOY_FAILED);
    }

    //生成10000-12000之间的随机数
    private int getPort() {
        int port;
        port = (int) (Math.random() * 2000 + 10000);
        while (isSocketAliveUitlitybyCrunchify(ip, port)) {
            port = (int) (Math.random() * 2000 + 10000);
        }
        return port;
    }
}
